﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DH.Core;
using DH.Entity;
using DH.Service.Domain;
using DH.Service.ViewModels;
using DH.Web.Attributes;
using DH.Web.Controllers;
using DH.Web.MVC.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using NLog;
using System.ComponentModel;

namespace DH.Web.MVC.Controllers
{
    [Authorize]
    [Route("Menu")]
    [Resource("菜单(资源)")]
    [Guid("53a79e79-0812-4c71-a8ea-3edcfb95d64e")]
    public class MenuController : SiteController<MenuEntity, MenuViewModel, string>
    {
        protected MenuService _menuService;
        protected PrivilegeService _privilegeService;
        //protected IServiceCollection _service;
        
        static Logger Logger = LogManager.GetCurrentClassLogger();
        public MenuController(IServiceCollection serviceCollection,
                              MenuService menuService) : base(serviceCollection, menuService)
        {
            //_service = serviceCollection;
            _menuService = menuService;

            _privilegeService = _service.BuildServiceProvider().GetService<PrivilegeService>();
            
        }

        [HttpGet]
        [Route("Index")]
        [UIView("菜单管理首页")]
        [Description("菜单管理首页")]
        [Guid("98694e1e-3ee5-4306-9279-8a60afa07672")]
        public IActionResult Index()
        {
            ViewBag.CurrentUser = CurrentUserEx;
            ViewBag.CurrentViewId = "98694e1e-3ee5-4306-9279-8a60afa07672";

            return View();
        }

        [HttpGet]
        [Route("Menus")]
        [Function("获取菜单列表")]
        [Description("获取菜单列表")]
        [Guid("e42878d7-b1aa-4a53-aad9-742cdd092d93")]
        public async Task<IActionResult> GetMenuListAsync() {

            PagedData<MenuViewModel> models;
            var pagination = GetPagination();
            var queryKey = Request.Query["queryKey"][0];
            var menuId = Request.Query["treeId"][0];

            var isDeveloper = CurrentUserEx.IsDeveloper;

            var res = await _menuService.GetListAsync(queryKey,menuId,pagination,isDeveloper);
            models = res.ToViewModelPageData<MenuEntity, MenuViewModel>();
            foreach (var m in models.DataList) {
                
                m.ParentName = "";
                if (!string.IsNullOrWhiteSpace(m.ParentId))
                {
                    var parentModel = _menuService.GetModelById(m.ParentId);
                    if (parentModel != null && parentModel.Status == true)
                    {
                        m.ParentName = parentModel.Name;
                    }
                }
                else {
                    m.ParentId = "";
                }
                
            }

            var result = new { total = models.TotalCount, rows = models.DataList };
            return Json(result);
        }

        [HttpPost]
        [Route("Add")]
        [Function("添加/编辑菜单",isManage:true)]
        [Description("添加/编辑菜单")]
        [Guid("8fcd292f-6465-42ee-83ed-f85c6b372ad4")]
        public async Task<IActionResult> Add(MenuViewModel input) {
            if (!ModelState.IsValid)
            {
                return ErrorMessage("实体类验证失败");
            }
            try
            {
                if (!string.IsNullOrWhiteSpace(input.Id))
                {
                    await _menuService.EditAsync(input);
                }
                else
                {
                    input.UpdatedBy = CurrentUser.UserId;
                    input.CreatedBy = CurrentUser.UserId;
                    await _menuService.AddAsync(input);
                }

                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("新增菜单时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while add menu wit data:", nameof(RoleViewModel));
            }
        }

        [HttpPost]
        [Route("Delete")]
        [Function("删除菜单", isManage: true)]
        [Description("删除菜单")]
        [Guid("ba49fa91-bb44-4b55-9ab3-798ce1b8229c")]

        public async Task<IActionResult> Delete(string[] ids)
        {
            try
            {
                //删除菜单
                await _menuService.DeleteAsync(ids);

                //删除角色菜单
                ///todo:删除角色菜单
                _privilegeService.DeleteMenuRelevance(ids);
                
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("删除角色发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while loading {0}", ids);
            }
        }

        [HttpGet]
        [Route("GetMenuSelects")]
        [Function("获取父级菜单")]
        [Description("获取父级菜单")]
        [Guid("b4fb06d7-d701-40cf-bd84-d0e08c73778d")]
        public async Task<IActionResult> GetMenuSelects()
        {
            var isDeveloper = CurrentUserEx.IsDeveloper;

            var res = await _menuService.GetMenuSelectsAsync(isDeveloper);
            return Json(res);
        }

        [HttpGet]
        [Route("GetMenuTree")]
        [Function("获取菜单树")]
        [Description("获取菜单树")]
        [Guid("125cdd41-fd66-472e-902c-a99860188887")]
        public async Task<IActionResult> GetMenuTree()
        {
            var isDeveloper = CurrentUserEx.IsDeveloper;

            var res = await _menuService.GetMenusAsync(isDeveloper);
            return Json(res);
        }


        [HttpPost]
        [Route("EnableMenu")]
        [Function("启用菜单",isManage:true)]
        [Description("启用菜单")]
        [Guid("c51f1fbc-c1da-40cf-b589-50786cfdac93")]
        public async Task<IActionResult> Enable(string id) {
            try
            {
                await _menuService.EnableAsync(id);
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("启用菜单时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while enabling Menu with id: {0}", id);
            }
        }

        [HttpPost]
        [Route("DisAbleMenu")]
        [Function("禁用菜单", isManage: true)]
        [Description("禁用菜单")]
        [Guid("7090990a-6116-4e6a-abd5-db0ac0d827e5")]
        public async Task<IActionResult> DisAble(string id) {
            try
            {
                await _menuService.DisableAsync(id);
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("禁用菜单时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while disabling Menu with id: {0}", id);
            }
        }

        [HttpGet]
        [Route("GetRootMenu")]
        [Function("获取用户管理界面菜单",isManage:false)]
        [Description("获取用户管理界面菜单")]
        [Guid("67a31ce8-8fb2-43a3-a688-d88145dfeb21")]
        public async Task<IActionResult> GetRootMenu()
        {
            
            try
            {
                var currentUserMenus = new List<string>();
                if (!CurrentUserEx.IsDeveloper)
                {
                    currentUserMenus = CurrentUserEx.RoleMenus.Select(c => c.ObjectId).ToList();
                }
                
                var res =await _menuService.GetRootMenuAsync(CurrentUserEx.IsDeveloper,currentUserMenus);
                
                return SuccessMessage(res,"执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("获取用户管理界面菜单时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while loading Menu ");
            }
        }
    }
}